package xyz.quanguanjia.masterboy.me;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import java.util.List;

import xyz.quanguanjia.masterboy.base.BaseFragment;
import xyz.quanguanjia.masterboy.decoration.HomeItemDecoration;
import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;
import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.MBDLoginActivity;
import xyz.quanguanjia.masterboy.MBDNotificationCenter;
import xyz.quanguanjia.masterboy.MBDPersonalInfoActivity;
import xyz.quanguanjia.masterboy.MBDPostListActivity;
import xyz.quanguanjia.masterboy.MBDSettingActivity;
import xyz.quanguanjia.masterboy.MBDUserCenter;
import xyz.quanguanjia.masterboy.MainActivity;
import xyz.quanguanjia.masterboy.MineCellItemModel;
import xyz.quanguanjia.masterboy.MineListAdapter;
import xyz.quanguanjia.masterboy.R;

public class MineFragment extends BaseFragment implements HomeItemDecoration.HomeItemClickListener {

    private RecyclerView recyclerView;
    private List<MineCellItemModel> models;

    private BroadcastReceiver loginSuccessReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 接收到登录成功的广播，执行刷新操作
            if (MBDNotificationCenter.NOTIFICATION_UPDATE_USERINFO.equals(intent.getAction())) {
                // 在这里更新头像等信息
                updateUserInfo();
            }
        }
    };

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        // 注册广播接收器
        IntentFilter filter = new IntentFilter(MBDNotificationCenter.NOTIFICATION_UPDATE_USERINFO);
        LocalBroadcastManager.getInstance(requireContext()).registerReceiver(loginSuccessReceiver, filter);

    }


    @Override
    public String fragmentTitle() {
        return "我的";
    }

    @Override
    public int fragmentIconId(int status) {
        if (status == BaseFragment.NORMAL) {
            return R.drawable.tab_mine_nm;
        }
        if (status == BaseFragment.HIGHLIGHT) {
            return R.drawable.tab_mine_hl;
        }
        return 0;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.models = MineListAdapter.defaultModels();

    }

    private void updateUserInfo() {
        this.models = MineListAdapter.defaultModels();
        MineListAdapter mineListAdapter = new MineListAdapter(this.models);
        recyclerView.setAdapter(mineListAdapter);

    }


    public static MBDAccountInfoModel convertLinkedTreeMapToAccountInfoModel(LinkedTreeMap<String, Object> linkedTreeMap) {
        Gson gson = new Gson();
        String jsonString = gson.toJson(linkedTreeMap);
        return gson.fromJson(jsonString, MBDAccountInfoModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        this.recyclerView = view.findViewById(R.id.recyclerView_mine);

        // 设置上拉加载更多监听器
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 在这里判断是否到达列表底部，触发加载更多的操作
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(MBDApplication.getContext());
        recyclerView.setLayoutManager(layoutManager);
        HomeItemDecoration hi = new HomeItemDecoration(this);
        recyclerView.addItemDecoration(hi);
        recyclerView.addItemDecoration(new DividerItemDecoration(MBDApplication.getContext(), LinearLayoutManager.VERTICAL));

        MineListAdapter mineListAdapter = new MineListAdapter(this.models);
        this.recyclerView.setAdapter(mineListAdapter);

        return view;

    }

    @Override
    public void onItemClick(int position) {
        MineCellItemModel model = this.models.get(position);
        switch (model.type) {
            case MineListAdapter.TYPE_AVATAR: {

                if (MBDUserCenter.shared().userInfoFetched()) {
                    Intent intent = new Intent(getActivity(), MBDPersonalInfoActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), MBDLoginActivity.class);

                    //在Fragment里调用startActivityForResult，就必须在Fragment里处理onActivityResult.
                    startActivityForResult(intent, MainActivity.LOGIN_REQUEST_CODE);
                    //present 动画
                    getActivity().overridePendingTransition(R.anim.slide_bottom_to_top_enter, R.anim.slide_no_anim);

                }

            }
            break;
            case MineListAdapter.TYPE_SETTING: {
                Intent intent = new Intent(getContext(), MBDSettingActivity.class);
                startActivity(intent);
            }
            break;
            case MineListAdapter.TYPE_PUBLISH: {
                if (MBDUserCenter.shared().userInfoFetched()) {
                    Intent intent = new Intent(getContext(), MBDPostListActivity.class);
                    startActivity(intent);
                } else {

                    Intent intent = new Intent(getActivity(), MBDLoginActivity.class);

                    //在Fragment里调用startActivityForResult，就必须在Fragment里处理onActivityResult.
                    startActivityForResult(intent, MainActivity.LOGIN_REQUEST_CODE);
                    //present 动画
                    getActivity().overridePendingTransition(R.anim.slide_bottom_to_top_enter, R.anim.slide_no_anim);
                }
            }
            break;
            case MineListAdapter.TYPE_INTEGRATE: {
                if (MBDUserCenter.shared().userInfoFetched()) {
                    Intent intent = new Intent(getContext(), MBDIntegrateActivity.class);
                    startActivity(intent);
                } else {

                    Intent intent = new Intent(getActivity(), MBDLoginActivity.class);

                    //在Fragment里调用startActivityForResult，就必须在Fragment里处理onActivityResult.
                    startActivityForResult(intent, MainActivity.LOGIN_REQUEST_CODE);
                    //present 动画
                    getActivity().overridePendingTransition(R.anim.slide_bottom_to_top_enter, R.anim.slide_no_anim);
                }
            }
            break;
            default:
                break;
        }


    }


    public interface RequestCallBack {
        public void completion(MBDAccountInfoModel accountInfoModel);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(this.loginSuccessReceiver);
    }
}
